package com.efivestar.idm.api.service.lock.protocol.handler;

import com.efivestar.idm.api.common.Cons;
import com.efivestar.idm.api.domain.DeviceDomain;
import com.efivestar.idm.api.service.DeviceService;
import com.efivestar.idm.api.service.IotService;
import com.efivestar.idm.api.util.ByteUtils;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 通信测试指令
 * <p>
 * 作用：设备初始化时测试设备端与服务端通信是否正常
 * <p>
 * 处理逻辑：服务端收到该报文时直接下发命令发送如下固定格式报文即可(EF01FFFFFFFF07000366006A)
 */
@Service
public class CommunicateProtocolHandler extends AbstractLockProtocolHandler {

    @Autowired
    private DeviceService deviceService;

    /**
     * @param buf
     * @param lockId
     * @return
     */
    @Override
    public byte[] handleData(ByteBuf buf, String lockId) {
        try {
            DeviceDomain deviceDomain = deviceService.getDeviceById(lockId);
            if (null != deviceDomain) {
                String iotDeviceId = deviceDomain.getIotDeviceId();
                if (StringUtils.isNotBlank(iotDeviceId)) {// 如果 iotDeviceId 不为空，则发送命令
                    String hex = deviceDomain.getProtocolHeader() + "FFFFFFFF070004" + Cons.UDP_COMMAND_COMUNICATE_TEST + "01";
                    IotService.postAsynCommandV4(iotDeviceId, "REMOTE_UNLOCK", "{\"remote_unlock_status\":\"" + hex + "\"}");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ByteUtils.hexToBytes("01");
    }

    @Override
    protected int getDataLenthWithoutDeviceId() {
        return 1;
    }

    @Override
    public String udpHead() {
        return Cons.UDP_HEAD_EF01;
    }

    @Override
    public String udpCommand() {
        return Cons.UDP_COMMAND_COMUNICATE_TEST;
    }

}






